package com.qiku.web.servlet;

import com.qiku.pojo.User;
import com.qiku.service.UserService;
import com.qiku.service.impl.UserServiceImpl;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.SQLException;

@WebServlet(name = "loginServlet",urlPatterns = "/login")
public class LoginServlet extends HttpServlet {
    /**
     * @param req  将于接受前端页面发送来的数据
     * @param resp 用于将后端处理后的结果  返回给前端页面
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            //解决中文乱码问题
            req.setCharacterEncoding("utf-8");
            //使用req接受参数
            String username = req.getParameter("username");
            String password = req.getParameter("password");
            //创建UserService 对象
            UserService userService = new UserServiceImpl();
            //将获取到的参数 username 和 password 作为参数  调用userService.login()
            User user = userService.userLogin(username,password);
            //拿到返回值  并解析  做出相应的处理
            //如果用户名和密码有一个不对 则user 就为 null
            if (user == null){
                //登陆失败 返回提示信息
                req.setAttribute("msg","用户名或者密码不正确！");
                //转发到登陆页面
                req.getRequestDispatcher("login.jsp").forward(req,resp);
            }else{
                //登陆成功  将登录成功的信息保存session
                //获取session
                HttpSession session = req.getSession();
                //将登陆成功的信息保存session中
                session.setAttribute("user", user);
                session.setAttribute("username",user.getUsername());
                //重定向到 index.jsp
                if (user.getIs_root() != 1) {
                    resp.sendRedirect("main.jsp");
                }else {
                    resp.sendRedirect("main2.jsp");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }

}
